package com.glory.brepda.adapter;

import static com.glory.brepda.utils.ShowDialog.showImagePreviewDialog;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.entity.EqpKeepInputListBean;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

public class EqpKeepInputListAdapter extends BaseQuickAdapter<EqpKeepInputListBean, BaseViewHolder> {
    private List<String> outData = new ArrayList<>();
    private OnUploadClickListener uploadClickListener;

    public EqpKeepInputListAdapter(@Nullable List<EqpKeepInputListBean> data, OnUploadClickListener listener) {
        super(R.layout.adapter_keep_check_list,data);
        this.uploadClickListener = listener;
    }

    @Override
    protected void convert(BaseViewHolder helper, EqpKeepInputListBean item) {
        helper.setText(R.id.tvItem1,item.getDataName() + "(" + item.getMinValue() + "/" + item.getMaxValue() + ")");
        helper.setText(R.id.tvItem2,item.getDescription());
        helper.setGone(R.id.tvItem3,true);
        helper.setText(R.id.tvItem3,item.getDataType());
        helper.setGone(R.id.etRemarks,true);
        EditText et = helper.getView(R.id.etRemarks);
        if (item.getDataType().equals("NUM")){
            et.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_SIGNED|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        }else {
            et.setInputType(InputType.TYPE_CLASS_TEXT);
        }
        if (et.getTag() instanceof TextWatcher) {
            et.removeTextChangedListener((TextWatcher) et.getTag());
        }
        et.setText(item.getDataString());
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length()>0)
                {
                    try {
                        item.setDataString(s.toString());
                        if (!item.getDataType().equals("TXT")){
                            double value = Double.parseDouble(s.toString());
                            compare(helper.getAdapterPosition(),value,item.getMaxValue(),item.getMinValue(),et);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        try {
            if (!item.getDataType().equals("TXT")) {
                double value = Double.parseDouble(item.getDataString());
                compare(helper.getAdapterPosition(), value, item.getMaxValue(), item.getMinValue(), et);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        et.addTextChangedListener(watcher);
        et.setTag(watcher);


        TextView upImage = helper.getView(R.id.upImage);
        ImageView showImage = helper.getView(R.id.showImage);
        upImage.setVisibility(View.VISIBLE);
        showImage.setVisibility(View.VISIBLE);
        upImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (uploadClickListener != null) {
                    uploadClickListener.onUploadClick(helper.getAdapterPosition());
                }
            }
        });
        String annexUrl = item.getImageUrl();
        if (!TextUtils.isEmpty(annexUrl)) {
            helper.setText(R.id.upImage, "更换");
            if (isBase64(annexUrl)) {
                try {
                    byte[] decodedBytes = Base64.decode(annexUrl, Base64.DEFAULT);
                    Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
                    showImage.setImageBitmap(decodedBitmap);
                } catch (Exception e) {
                    e.printStackTrace(); // 可选：日志
                }
            }
        }
        showImage.setOnClickListener(v -> {
            String base64 = item.getImageUrl();
            if (base64 == null || base64.isEmpty()) {
                return;
            }
            showImagePreviewDialog(helper.itemView.getContext(), base64);
        });

    }


    private void compare(int position,double value, String maxValue,String minValue,EditText editText){
        if (!FreeApi_StringUtils.isEmpty(maxValue)&&!FreeApi_StringUtils.isEmpty(minValue)){
            double maxValues = Double.parseDouble(maxValue);
            double minValues = Double.parseDouble(minValue);
            if(minValues<=value&&value<=maxValues) {
                editText.setTextColor(MyApp.app.getResources().getColor(R.color.black));
                if (outData.contains(String.valueOf(position))){
                    outData.remove(String.valueOf(position));
                }
            }else{
                editText.setTextColor(MyApp.app.getResources().getColor(R.color.red));
                if (!outData.contains(String.valueOf(position))){
                    outData.add(String.valueOf(position));
                }
            }
        }else if (FreeApi_StringUtils.isEmpty(maxValue)&&!FreeApi_StringUtils.isEmpty(minValue)){
            double minValue1 = Double.parseDouble(minValue);
            if (value >= minValue1){
                editText.setTextColor(MyApp.app.getResources().getColor(R.color.black));
                if (outData.contains(String.valueOf(position))){
                    outData.remove(String.valueOf(position));
                }
            }else{
                editText.setTextColor(MyApp.app.getResources().getColor(R.color.red));
                if (!outData.contains(String.valueOf(position))){
                    outData.add(String.valueOf(position));
                }
            }
        }else if (!FreeApi_StringUtils.isEmpty(maxValue)&&FreeApi_StringUtils.isEmpty(minValue)){
            double maxValue1 = Double.parseDouble(maxValue);
            if (value <= maxValue1){
                editText.setTextColor(MyApp.app.getResources().getColor(R.color.black));
                if (outData.contains(String.valueOf(position))){
                    outData.remove(String.valueOf(position));
                }
            }else{
                editText.setTextColor(MyApp.app.getResources().getColor(R.color.red));
                if (!outData.contains(String.valueOf(position))){
                    outData.add(String.valueOf(position));
                }
            }
        }else {
            editText.setTextColor(MyApp.app.getResources().getColor(R.color.black));
        }
    }

    public List<String> getOutData(){
        return outData;
    }

    public void clearData(){
        outData.clear();
    }


    public interface OnUploadClickListener {
        void onUploadClick(int position);
    }

    public static boolean isBase64(String str) {
        // 判断字符串是否只包含 Base64 合法字符并且长度是4的倍数
        return str.matches("^[A-Za-z0-9+/=\\r\\n]+$") && str.length() % 4 == 0;
    }

}
